/**
 *@description CRM运营》数据
 *@author yhw
 */
import {
  saleMonth,
  saleArea,
  memberBack,
  areaMemberBack,
  memberActivity,
  memberCustomer,
  monthMember,
  areaMember,
  memberConsume,
  customerSingle,
  age,
  activity,
  product,
  monthProduct,
  areaProduct,
  storeVip,
  recruitMonth,
  AreaVipRecruit,
  WeChatVip,
  CurMonthPurMember,
  CurMonthRepPurMember
} from '../services/CRMdata';
import {
  parse
} from 'qs';
import error from '../utils/tips';
import {commafy,floatMul} from '../utils/utils';

export default {

  namespace: 'CRMdata',

  state: {
    //销售
    saleMonthData: null,
    saleMonthTableData: {},
    saleMonthDownloadData: null,
    saleMonthLoading: false,
    saleAreaTableData: {},
    saleAreaDownloadData: null,
    saleAreaLoading: false,


    //回柜
    memberBackLoading: false,
    memberBackChartData: null,
    memberBackData: {},
    memberBackDownloadData: null,
    areaMemberBackData: {},
    areaMemberBackDownloadData: null,
    memberActivityData: {},
    memberActivityDownloadData: null,
    memberCustomerData: {},
    memberCustomerDownloadData: null,
    memberCustomerLoading: false,

    //会员指标
    monthMemberData: {},
    monthMemberDownloadData: null,
    areaMemberData: {},
    areaMemberDownloadData: null,
    memberConsumeData: {},
    memberConsumeDownloadData: null,
    customerSingleData: {},
    customerSingleDownloadData: null,

    //活动效益
    activityData: {},
    activityDownloadData: null,

    //产品
    productLoading: false,
    productChartData: null,
    productData: {},
    productDownloadData: null,
    monthProductData: {},
    monthProductDownloadData: null,
    areaProductData: {},
    areaProductDownloadData: null,
    CurMonthPurMemberData: {},
    CurMonthPurMemberDownloadData: null,
    CurMonthRepPurMemberData: {},
    CurMonthRepPurMemberDownloadData: null,

    //会员基本信息
    ageData: {},
    ageDownloadData: null,
    ageLoading: false,

	// 店铺效能
    storeVipTableData: {},
    storeVipDownloadData: null,
    storeVipLoading: false,
    //月度会员招募
    recruitMonthTableData: {},
    recruitMonthDownloadData: null,
    recruitMonthLoading: false,
    //地区会员招募
    AreaVipRecruitTableData: {},
    AreaVipRecruitDownloadData: null,
    AreaVipRecruitLoading: false,
    //地区会员招募
    WeChatVipTableData: {},
    WeChatVipDownloadData: null,
    WeChatVipLoading: false
  },

  subscriptions: {},

  effects: {
    //销售
    * saleMonth({payload}, {call, put}) {
      yield put({type: 'saleMonthLoading'});
      let resData = yield call(saleMonth, parse(payload));
      let data = resData.data.data;

      if (data) {
        let chartData = getChartData(data);
        let saleMonthTableData = getTableData(data, 200);
        let saleMonthDownloadData = getDownloadData(data);

        yield put({
          type: 'saleMonthTableDataUpdate',
          payload: {
            saleMonthData: chartData,
            saleMonthTableData: saleMonthTableData,
            saleMonthDownloadData: saleMonthDownloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * saleArea({payload}, {call, put}){
      yield put({type: 'saleAreaLoading'});
      const resData = yield call(saleArea, parse(payload));
      let data = resData.data.data;
      let saleAreaTableData = getTableData(data, 200);
      let saleAreaDownloadData = getDownloadData(data);

      if(data){
        //data process
        yield put({
          type: 'saleAreaTableDataUpdate',
          payload: {
            saleAreaTableData: saleAreaTableData,
            saleAreaDownloadData: saleAreaDownloadData,
          }
        });
      }else{
        error("获取地区销售额失败");
      }
    },

    //回柜
    * memberBack({payload}, {call, put}) {
      yield put({
        type: 'commonDataUpdate',
        payload: {
          memberBackLoading: true,
        }
      });

      let resData = yield call(memberBack, parse(payload));
      let data = resData.data.data;

      if (data) {
        let chartData = getChartData(data, function(item){
          if(item.key && item.key.indexOf('回柜率') >= 0){
            return {type: 'line', yAxisIndex: 1};
          }else{
            return {type: 'bar', yAxisIndex: 0};
          }
        });
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);
        tableData.data.forEach(rowData => {
          if(rowData.name.indexOf('率') >= 0){
            for(let key in rowData){
              if(key != 'key' && key != 'name'){
                rowData[key] = floatMul(rowData[key],100) + '%';
              }
            }
          }
        });
        yield put({
          type: 'commonDataUpdate',
          payload: {
            memberBackChartData: chartData,
            memberBackData: tableData,
            memberBackDownloadData: downloadData,
            memberBackLoading: false,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * areaMemberBack({payload}, {call, put}) {
      let resData = yield call(areaMemberBack, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            areaMemberBackData: tableData,
            areaMemberBackDownloadData: downloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * memberActivity({payload}, {call, put}) {
      let resData = yield call(memberActivity, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            memberActivityData: tableData,
            memberActivityDownloadData: downloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * memberCustomer({payload}, {call, put}) {
      yield put({
        type: 'commonDataUpdate',
        payload: {
          memberCustomerLoading: true,
        }
      });
      let resData = yield call(memberCustomer, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            memberCustomerData: tableData,
            memberCustomerDownloadData: downloadData,
            memberCustomerLoading: false,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },

    //会员指标
    * monthMember({payload}, {call, put}) {

      let resData = yield call(monthMember, parse(payload));
      let data = resData.data.data;

      if (data) {

        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {

            monthMemberData: tableData,
            monthMemberDownloadData: downloadData,

          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * areaMember({payload}, {call, put}) {
      let resData = yield call(areaMember, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            areaMemberData: tableData,
            areaMemberDownloadData: downloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * memberConsume({payload}, {call, put}) {
      let resData = yield call(memberConsume, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            memberConsumeData: tableData,
            memberConsumeDownloadData: downloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },
    * customerSingle({payload}, {call, put}) {
      let resData = yield call(customerSingle, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            customerSingleData: tableData,
            customerSingleDownloadData: downloadData,
          },
        });

      } else {
        error("获取月度销售额失败");
      }
    },

    //活动效益
    * activity({payload}, {call, put}) {
      let resData = yield call(activity, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            activityData: tableData,
            activityDownloadData: downloadData,
          },
        });

      } else {
        error("年龄分布");
      }
    },

    //产品
    * product({payload}, {call, put}) {
      yield put({
        type: 'commonDataUpdate',
        payload: {
          productLoading: true,
        }
      });
      let resData = yield call(product, parse(payload));
      let data = resData.data.data;

      if (data) {
        let chartData = getChartData(data, 'bar');
        let tableData = getTableData(data, 100, '产品大类', false);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            productChartData: chartData,
            productData: tableData,
            productDownloadData: downloadData,
            productLoading: false,
          },
        });
      } else {
        error("年龄分布");
      }
    },
    * monthProduct({payload}, {call, put}) {
      let resData = yield call(monthProduct, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            monthProductData: tableData,
            monthProductDownloadData: downloadData,
          },
        });

      } else {
        error("年龄分布");
      }
    },
    * areaProduct({payload}, {call, put}) {
      let resData = yield call(areaProduct, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            areaProductData: tableData,
            areaProductDownloadData: downloadData,
          },
        });

      } else {
        error("年龄分布");
      }
    },
    * CurMonthPurMember({payload}, {call, put}) {
      let resData = yield call(CurMonthPurMember, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data,440);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            CurMonthPurMemberData: tableData,
            CurMonthPurMemberDownloadData: downloadData,
          },
        });

      } else {
        error("当月产品购买会员");
      }
    },
    //产品复购
    * CurMonthRepPurMember({payload}, {call, put}) {
      let resData = yield call(CurMonthRepPurMember, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data,440);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            CurMonthRepPurMemberData: tableData,
            CurMonthRepPurMemberDownloadData: downloadData,
          },
        });

      } else {
        error("产品复购");
      }
    },
    //会员基本信息
    * age({payload}, {call, put}) {
      yield put({
        type: 'commonDataUpdate',
        payload: {
          ageLoading: true,
        }
      });
      let resData = yield call(age, parse(payload));
      let data = resData.data.data;

      if (data) {
        let tableData = getTableData(data);
        let downloadData = getDownloadData(data);

        yield put({
          type: 'commonDataUpdate',
          payload: {
            ageData: tableData,
            ageDownloadData: downloadData,
            ageLoading: false,
          },
        });

      } else {
        error("年龄分布");
      }
    },

    //店铺效能
    * storeVip({payload}, {call, put}){
      yield put({type: 'storeVipLoading'});
      const resData = yield call(storeVip, parse(payload));
      let data = resData.data.data;
      let storeVipTableData = getTableData(data);
      let storeVipDownloadData = getDownloadData(data);

      if(data){
        //data process
        yield put({
          type: 'storeVipTableDataUpdate',
          payload: {
            storeVipTableData: storeVipTableData,
            storeVipDownloadData: storeVipDownloadData,
          }
        });
      }else{
        error("获取失败");
      }
    },
    //月度会员招募
    * recruitMonth({payload}, {call, put}){
      yield put({type: 'recruitMonthLoading'});
      const resData = yield call(recruitMonth, parse(payload));
      let data = resData.data.data;
      let chartData = getChartData(data, function(item){
        let extraKeys = {type: 'bar'};
        if(item.key == '总会员数'){

        }else if(item.key == '微信会员数' || item.key == 'POS会员数'){
          extraKeys.stack = 1;
        }else if(item.key == '有效会员数' || item.key == '新会员招募（有购买）'|| item.key == '新会员招募（无购买）'){
          extraKeys.stack = 2;
        }else if(item.key == '新会员中首单350以上招募' || item.key == '老会员维系数'|| item.key == '沉默会员数'){
          extraKeys.stack = 3;
        }
        // extraKeys.stack = item.stack;
        return extraKeys;
      });
      let recruitMonthTableData = getTableData(data);
      let recruitMonthDownloadData = getDownloadData(data);

      if(data){
        //data process
        yield put({
          type: 'recruitMonthTableDataUpdate',
          payload: {
            recruitMonthData: chartData,
            recruitMonthTableData: recruitMonthTableData,
            recruitMonthDownloadData: recruitMonthDownloadData,
          }
        });
      }else{
        error("获取月度会员招募失败");
      }
    },
    //地区会员招募
    * AreaVipRecruit({payload}, {call, put}){
      yield put({type: 'AreaVipRecruitLoading'});
      const resData = yield call(AreaVipRecruit, parse(payload));
      let data = resData.data.data;
      let AreaVipRecruitTableData = getTableData(data);
      let AreaVipRecruitDownloadData = getDownloadData(data);

      if(data){
        //data process
        yield put({
          type: 'AreaVipRecruitTableDataUpdate',
          payload: {
            AreaVipRecruitTableData: AreaVipRecruitTableData,
            AreaVipRecruitDownloadData: AreaVipRecruitDownloadData,
          }
        });
      }else{
        error("获取失败");
      }
    },

    //微信会员招募
    * WeChatVip({payload}, {call, put}){
      yield put({type: 'WeChatVipLoading'});
      const resData = yield call(WeChatVip, parse(payload));
      let data = resData.data.data;
      let WeChatVipTableData = getTableData(data);
      let WeChatVipDownloadData = getDownloadData(data);

      if(data){
        //data process
        yield put({
          type: 'WeChatVipTableDataUpdate',
          payload: {
            WeChatVipTableData: WeChatVipTableData,
            WeChatVipDownloadData: WeChatVipDownloadData,
          }
        });
      }else{
        error("获取失败");
      }
    },
    //===================================
  },

  reducers: {
    commonDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
      };
    },

    //销售
    saleMonthLoading(state) {
      return {...state,
        saleMonthLoading: true
      };
    },
    saleMonthSuccess(state, action) {
      return {...state,
        ...action.payload,
        saleMonthLoading: false
      };
    },
    saleMonthTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        saleMonthLoading: false,
      };
    },
    saleAreaLoading(state) {
      return {
        ...state,
        saleAreaLoading: true
      };
    },
    saleAreaTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        saleAreaLoading: false,
      };
    },
    saleAreaSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        saleAreaLoading: false,
      };
    },
	//店铺效能
    storeVipLoading(state) {
      return {...state,
        storeVipLoading: true
      };
    },
    storeVipTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        storeVipLoading: false,
    };
    },
    storeVipSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        storeVipLoading: false,
    };
    },
//当月购买会员
    CurMonthPurMemberLoading(state) {
      return {...state,
        CurMonthPurMemberLoading: true
      };
    },
    CurMonthPurMemberDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        CurMonthPurMemberLoading: false,
    };
    },
    CurMonthPurMemberSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        CurMonthPurMemberLoading: false,
    };
    },
//产品复购
    CurMonthRepPurMemberLoading(state) {
      return {...state,
        CurMonthRepPurMemberLoading: true
      };
    },
    CurMonthRepPurMemberDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        CurMonthRepPurMemberLoading: false,
    };
    },
    CurMonthRepPurMemberSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        CurMonthRepPurMemberLoading: false,
    };
    },
    //月度会员招募
    recruitMonthLoading(state) {
      return {...state,
        recruitMonthLoading: true
      };
    },
    recruitMonthTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        recruitMonthLoading: false,
    };
    },
    recruitMonthSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        recruitMonthLoading: false,
    };
    },
    //地区会员招募
    AreaVipRecruitLoading(state) {
      return {...state,
        AreaVipRecruitLoading: true
      };
    },
    AreaVipRecruitTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        AreaVipRecruitLoading: false,
    };
    },
    AreaVipRecruitSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        AreaVipRecruitLoading: false,
    };
    },
    //微信会员招募
    WeChatVipLoading(state) {
      return {...state,
        WeChatVipLoading: true
      };
    },
    WeChatVipTableDataUpdate(state, action){
      return {
        ...state,
        ...action.payload,
        WeChatVipLoading: false,
    };
    },
    WeChatVipSuccess(state, action){
      return {
        ...state,
        ...action.payload,
        WeChatVipLoading: false,
    };
    },

  },

};

function getTableData(data, width, headerName, fixed){
  let tableData = {
    columns: [],
    data: [],
  };
  let column = {title: headerName || '指标', width: width || 190, dataIndex: 'name', key: 'name'};
  if(typeof fixed == 'undefined'){
    fixed = 'left';
  }
  if(fixed === false){
    fixed = '';
  }
  if(fixed){
    column.fixed = fixed;
  }

  tableData.columns.push(column);

  data.forEach((item, index) => {
    let tableRowData = {};
    tableRowData.key = index;
    tableRowData.name = item.key;

    tableData.data.push(tableRowData);

    item.value.forEach((itemData, index2) => {
      if(index === 0){
        tableData.columns.push({
          title: itemData.key,
          dataIndex: index2,
          key: 'col-' + index2,
        });
      }
      tableRowData[index2] = commafy(itemData.value);

    });

  });

  return tableData;
}

function getDownloadData(data, headerName){
  let tableData = {
    header: [],
    data: [],
  };

  tableData.header.push(headerName || '指标');

  data.forEach((item, index) => {
    let tableRowData = [];
    tableRowData.push(item.key);
    tableData.data.push(tableRowData);

    item.value.forEach((itemData) => {
      if(index === 0){
        tableData.header.push(itemData.key);
      }
      tableRowData.push(itemData.value);
    });
  });

  return tableData;
}

function getChartData(data, type){
  let chartData = {
    xAxisData: [],
    legend: [],
    series: [],
  };

  data.forEach((item, index) => {
    let seriesItemType = '';
    let mutilsType = null;
    //chart数据
    if(typeof type == 'function'){
      mutilsType = type(item);
      seriesItemType = mutilsType.type;
    }else{
      seriesItemType = type || 'line';
    }

    chartData.legend.push(item.key);
    let seriesItem = {
      name: item.key,
      type: seriesItemType,
      data: [],
    };

    if(mutilsType){
      if(mutilsType.yAxisIndex){
        seriesItem.yAxisIndex = mutilsType.yAxisIndex;
      }

      if(mutilsType.stack){
        seriesItem.stack = mutilsType.stack;
      }
    }

    chartData.series.push(seriesItem);

    item.value.forEach(itemData => {
      if(index === 0){
        chartData.xAxisData.push(itemData.key);
      }
      seriesItem.data.push(itemData.value);
    });
  });

  return chartData;
}
